<?php
require_once('config.php');


function connect_db() {
    global $config;
    $link = mysql_connect($config->host, $config->user , $config->password ) or die ('Error on DB 1');
    $db = mysql_select_db($config->dbname, $link);
    return $link;
}


function save(){
    $id = checkLogin();
    if ($_POST['name'] && $_POST['xml']) {
        $filename = './maps/'.$id.'/'.$_POST['name'].'.xml.gz';
        $content = gzencode($_POST['xml'],9);

        $fp = fopen($filename,'w');
        fwrite ($fp,$content, strlen($content));
        fclose($fp);

        print "1";
    }
}

function getFiles(){
    $id = checkLogin();
    $dir = opendir('./maps/'.$id);
    print '<h2>Select a file</h2>';
    print '<select id="filelist" size="10" style="width: 100%">';
    while($file = readdir($dir)) {
        //print $file;
        if(is_file('./maps/'.$id.'/'.$file) && preg_match('/.xml.gz$/',$file)){
            $file = preg_replace('/.xml.gz$/','',$file);
            print '<option value="'.basename($file).'">'.basename($file).'</option>';
        }
    }
    print '</select>';
}

function open(){


}

function createAccount(){
    $db = connect_db();
    $res = mysql_query("select id from users where name='".mysql_real_escape_string($_REQUEST['login'])."'", $db);
    if (mysql_num_rows($res) > 0){
        print "Username already exists";
        exit();
    }
    else if (empty($_REQUEST['login']) || empty($_REQUEST['password']) ||empty($_REQUEST['mail']) ){
        print "Please, provides login, password and mail address to perform registration";
        exit();
    }
    else {
        $res = mysql_query("insert into users (name,password,mail) values ("
                ."'".mysql_real_escape_string($_REQUEST['login'])."',"
                ."'".md5(mysql_real_escape_string($_REQUEST['password']))."',"
                ."'".mysql_real_escape_string($_REQUEST['mail'])."'"
                ." )"
        ,$db);

        //create user dir
        $id = mysql_insert_id();
        mkdir('./maps/'.$id,0765);
        file_put_contents('./maps/'.$id.'/.htaccess',"Options Indexes");
        $_SESSION['id'] = $id;
        $_SESSION['login'] = $_REQUEST['login'];
    }
    print 1;
}


function login() {
    //only check login
    if(empty($_REQUEST['login'])){
        if(!empty($_SESSION['id']) && !empty($_SESSION['login'])){
            print $_SESSION['login']; exit;
        }
        print 0; exit;
    }

    $db = connect_db();
    $res = mysql_query("select id from users where name='"
            .mysql_real_escape_string($_REQUEST['login'])
            ."' and password = '"
            .md5(mysql_real_escape_string($_REQUEST['password']))."'", $db);

    if (mysql_num_rows($res) < 1){
        print "Bad Login or password";
        exit();
    }
    $user = mysql_fetch_object($res);
    $_SESSION['id'] = $user->id;
    $_SESSION['login'] = $_REQUEST['login'];

    print 1;

}


function getContent($return=false){
    $id = checkLogin();
    $filename = $_REQUEST['filename'];
    //if(!preg_match('/.xml.gz$/',$filename)) die('Error on open file 2');

    $xml = gzdecode(file_get_contents('./maps/'.$id.'/'.$filename.".xml.gz"));
    if(!$return) {
        print $xml;
        flush(); exit;
    }
    return $xml;
}

function checkLogin(){
   if (empty($_SESSION['id']) || empty($_SESSION['login'])) {
        exit ('Not logged');
   }
   return $_SESSION['id'];
}


function getXML(){
    global $config;
    header('Content-type: text/xml');
    $filename = $_REQUEST['filename'];
    header('Content-Disposition: attachment; filename="'.$filename.'.xml"');
    $xml = getContent(true);
    $temp = $config->temp_dir.'/'.uniqid('mind').$filename.".xml";
    file_put_contents($temp,$xml);
    $xml = `xmllint --format $temp`;
    print $xml;
}


//see http://www.php.net/manual/en/function.gzencode.php#44470
//gzdecode is currently only usable from PHP >= 6
//this function add gzencode to PHP >=5


function gzdecode($data) {
  $len = strlen($data);
  if ($len < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) {
    return null;  // Not GZIP format (See RFC 1952)
  }
  $method = ord(substr($data,2,1));  // Compression method
  $flags  = ord(substr($data,3,1));  // Flags
  if ($flags & 31 != $flags) {
    // Reserved bits are set -- NOT ALLOWED by RFC 1952
    return null;
  }
  // NOTE: $mtime may be negative (PHP integer limitations)
  $mtime = unpack("V", substr($data,4,4));
  $mtime = $mtime[1];
  $xfl   = substr($data,8,1);
  $os    = substr($data,8,1);
  $headerlen = 10;
  $extralen  = 0;
  $extra     = "";
  if ($flags & 4) {
    // 2-byte length prefixed EXTRA data in header
    if ($len - $headerlen - 2 < 8) {
      return false;    // Invalid format
    }
    $extralen = unpack("v",substr($data,8,2));
    $extralen = $extralen[1];
    if ($len - $headerlen - 2 - $extralen < 8) {
      return false;    // Invalid format
    }
    $extra = substr($data,10,$extralen);
    $headerlen += 2 + $extralen;
  }

  $filenamelen = 0;
  $filename = "";
  if ($flags & 8) {
    // C-style string file NAME data in header
    if ($len - $headerlen - 1 < 8) {
      return false;    // Invalid format
    }
    $filenamelen = strpos(substr($data,8+$extralen),chr(0));
    if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {
      return false;    // Invalid format
    }
    $filename = substr($data,$headerlen,$filenamelen);
    $headerlen += $filenamelen + 1;
  }

  $commentlen = 0;
  $comment = "";
  if ($flags & 16) {
    // C-style string COMMENT data in header
    if ($len - $headerlen - 1 < 8) {
      return false;    // Invalid format
    }
    $commentlen = strpos(substr($data,8+$extralen+$filenamelen),chr(0));
    if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {
      return false;    // Invalid header format
    }
    $comment = substr($data,$headerlen,$commentlen);
    $headerlen += $commentlen + 1;
  }

  $headercrc = "";
  if ($flags & 2) {
    // 2-bytes (lowest order) of CRC32 on header present
    if ($len - $headerlen - 2 < 8) {
      return false;    // Invalid format
    }
    $calccrc = crc32(substr($data,0,$headerlen)) & 0xffff;
    $headercrc = unpack("v", substr($data,$headerlen,2));
    $headercrc = $headercrc[1];
    if ($headercrc != $calccrc) {
      return false;    // Bad header CRC
    }
    $headerlen += 2;
  }

  // GZIP FOOTER - These be negative due to PHP's limitations
  $datacrc = unpack("V",substr($data,-8,4));
  $datacrc = $datacrc[1];
  $isize = unpack("V",substr($data,-4));
  $isize = $isize[1];

  // Perform the decompression:
  $bodylen = $len-$headerlen-8;
  if ($bodylen < 1) {
    // This should never happen - IMPLEMENTATION BUG!
    return null;
  }
  $body = substr($data,$headerlen,$bodylen);
  $data = "";
  if ($bodylen > 0) {
    switch ($method) {
      case 8:
        // Currently the only supported compression method:
        $data = gzinflate($body);
        break;
      default:
        // Unknown compression method
        return false;
    }
  } else {
    // I'm not sure if zero-byte body content is allowed.
    // Allow it for now...  Do nothing...
  }

  // Verifiy decompressed size and CRC32:
  // NOTE: This may fail with large data sizes depending on how
  //       PHP's integer limitations affect strlen() since $isize
  //       may be negative for large sizes.
  if ($isize != strlen($data) || crc32($data) != $datacrc) {
    // Bad format!  Length or CRC doesn't match!
    return false;
  }
  return $data;
}











